package com.itheima.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.MemberService;
import com.itheima.service.ReportService;
import com.itheima.service.SetmealService;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 报表
 *
 * @author Chengfei
 * @date 2020/08/18
 */
@RestController
@RequestMapping("/report")
public class ReportController {

    @Reference
    private MemberService memberService;
    @Reference
    private SetmealService setmealService;
    @Reference
    private ReportService reportService;

    /**
     * 会员数据统计 (按照过去一年时间内每个月的会员总数据量)
     * @return Map<String,Object> 键为 字符串 值为 集合等
     */
    @RequestMapping("/getMemberReport")
    public Result getMemberReport() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, -12);

        //遍历,得到过去一年每个月的年/月份
        List<String> list = new ArrayList<>();
        for (int i = 0; i < 12; i++) {
            calendar.add(Calendar.MONTH, 1);
            list.add(new SimpleDateFormat("yyyy.MM").format(calendar.getTime()));
        }
        //将月份集合放到map中
        Map<String, Object> map = new HashMap<>(2);
        map.put("months", list);
        //将每个月 月份 会员数集合翻到map中
        List<Integer> memberCount = memberService.findMemberCountByMonth(list);
        map.put("memberCount", memberCount);

        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
    }

    /**
     * 会员数据统计 (按照过去每一天的会员总数据量)
     * @return  Map<String,Object> 键为 字符串 值为 集合等
     */
    @RequestMapping("/getMemberReportByEveryday")
    public Result getMemberReportByEveryday() {
        //返回的结果集合
        Map<String, Object> map = new HashMap<>(2);
        //存放月份的集合
        List<String> months = new ArrayList<>();
        //存放月份 会员数 的集合
        List<Object> memberCount = new ArrayList<>();

        List<Map<String, String>> mapLists = memberService.getMemberReportByEveryday();
        for (Map<String, String> mapList : mapLists) {

            Object regTimeDB = mapList.get("regTime");
            String strRegTimeDB = regTimeDB.toString().substring(0, 10);
            Object countDB = mapList.get("count");

            months.add(strRegTimeDB);
            memberCount.add(countDB);
        }

        map.put("months", months);
        map.put("memberCount", memberCount);

        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
    }

    /**
     * 套餐预约占比饼状图
     * @return  Map<String, list>  套餐名称  占比
     */
    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport() {

        //查询所有套餐姓名
        List<Map<String, Object>> list = setmealService.findSetmealCount();

        //返回的数据类型
        Map<String, Object> map = new HashMap<>(2);

/*        因前端数据可不需要单独套餐名,故不需要处理
        //所有套餐的名称
        List<String> setmealNames = new ArrayList<>();
        for (Map<String, Object> m : list) {
            String name = (String) m.get("name");
            setmealNames.add(name);
        }
        map.put("setmealNames", setmealNames);*/

        map.put("setmealCount", list);

        return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS, map);
    }

    /**
     * 运营数据统计
     * @return  Map<String, Object> 运营的统计数据
     * @throws Exception
     */
    @RequestMapping("/getBusinessReportData")
    public Result getBusinessReportData() throws Exception {

        try {
            Map<String, Object> map = reportService.getBusinessReportData();
            return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }

    }

    /**
     * 运营数据统计导出到Excel中 提供客户端下载
     * @param request  用于获取模板的绝对路径
     * @param response 写出数据流到客户端
     * @return
     */
    @RequestMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response) {

        try {
            //远程调用报表获取数据
            Map<String, Object> result = reportService.getBusinessReportData();

            //取出报表需要数据
            String reportDate = (String) result.get("reportDate");
            Integer todayNewMember = (Integer) result.get("todayNewMember");
            Integer totalMember = (Integer) result.get("totalMember");
            Integer thisWeekNewMember = (Integer) result.get("thisWeekNewMember");
            Integer thisMonthNewMember = (Integer) result.get("thisMonthNewMember");
            Integer todayOrderNumber = (Integer) result.get("todayOrderNumber");
            Integer thisWeekOrderNumber = (Integer) result.get("thisWeekOrderNumber");
            Integer thisMonthOrderNumber = (Integer) result.get("thisMonthOrderNumber");
            Integer todayVisitsNumber = (Integer) result.get("todayVisitsNumber");
            Integer thisWeekVisitsNumber = (Integer) result.get("thisWeekVisitsNumber");
            Integer thisMonthVisitsNumber = (Integer) result.get("thisMonthVisitsNumber");
            List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");

            //获得Excel模板文件的路径            File.separator自动适应操作系统,相当于分隔符   windows \  Linux  /
            String templateRealPath = request.getSession().getServletContext().getRealPath("template" + File.separator + "report_template.xlsx");

            //读取模板文件,创建Excel表格对象
            XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(templateRealPath));
            XSSFSheet sheet = workbook.getSheetAt(0);

            //表格第二行,第五列  日期
            XSSFRow row = sheet.getRow(2);
            row.getCell(5).setCellValue(reportDate);

            row = sheet.getRow(4);
            //今日新增会员数
            row.getCell(5).setCellValue(todayNewMember);
            //总会员数
            row.getCell(7).setCellValue(totalMember);

            row = sheet.getRow(5);
            //本周新增会员数
            row.getCell(5).setCellValue(thisWeekNewMember);
            //本月新增会员数
            row.getCell(7).setCellValue(thisMonthNewMember);

            row = sheet.getRow(7);
            //今日预约数
            row.getCell(5).setCellValue(todayOrderNumber);
            //今日到诊数
            row.getCell(7).setCellValue(todayVisitsNumber);

            row = sheet.getRow(8);
            //本周预约数
            row.getCell(5).setCellValue(thisWeekOrderNumber);
            //本周到诊数
            row.getCell(7).setCellValue(thisWeekVisitsNumber);

            row = sheet.getRow(9);
            //本月预约数
            row.getCell(5).setCellValue(thisMonthOrderNumber);
            //本月到诊数
            row.getCell(7).setCellValue(thisMonthVisitsNumber);

            //12行开始热门套餐 4-7
            int rowNum = 12;
            for (Map map : hotSetmeal) {
                String name = (String) map.get("name");
                Long setmealCount = (Long) map.get("setmeal_count");
                BigDecimal proportion = (BigDecimal) map.get("proportion");

                row = sheet.getRow(rowNum++);
                //套餐名称
                row.getCell(4).setCellValue(name);
                //预约数量
                row.getCell(5).setCellValue(setmealCount);
                //占比
                row.getCell(6).setCellValue(proportion.doubleValue());
            }

            //通过输出流进行文件下载
            ServletOutputStream out = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");//代表的是Excel文件类型   ms 是microsoft缩写
            response.setHeader("content-Disposition","attachment;filename=report.xlsx");
            workbook.write(out);

            out.flush();
            out.close();
            workbook.close();

            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }

    }

    /**
     * 运营数据统计导出到PDF中 提供客户端下载
     * @param request   用于获取模板的绝对路径
     * @param response  写出数据流到客户端
     * @return  PDF文件
     */
    @RequestMapping("/exportBusinessReport4PDF")
    public Result exportBusinessReport4PDF(HttpServletRequest request, HttpServletResponse response) {

        try {
            //查询数据库,得到运营统计数据
            Map<String, Object> result = reportService.getBusinessReportData();

            //取出返回结果数据 准备将数据写入PDF文件中
            List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");

            //动态获取模板文件
            String jrxmlPath = request.getSession().getServletContext().getRealPath("template" + File.separator + "health_business3.jrxml");
            String jasperPath = request.getSession().getServletContext().getRealPath("template" + File.separator + "health_business3.jasper");
            //编译模板
            JasperCompileManager.compileReportToFile(jrxmlPath,jasperPath);

            //填充数据  使用JavaBean数据源方式填充
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperPath,result,new JRBeanCollectionDataSource(hotSetmeal));

            //输出流给客户端  (固定写法)
            ServletOutputStream out = response.getOutputStream();
            response.setContentType("application/pdf");
            response.setHeader("content-Disposition","attachment;filename=report.pdf");

            //输出文件
            JasperExportManager.exportReportToPdfStream(jasperPrint,out);

            out.close();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }

    }

}
